package com.besttone.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;

import com.besttone.common.StaticConstantType;
import com.besttone.model.BstShortlinkRequest;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;

public class ShortlinkBrowseRecord2SolrUtil {

    private static Log _log = LogFactory
	    .getLog(ShortlinkBrowseRecord2SolrUtil.class);
    private static CloudSolrServer cloudSolrServer;
    private static Cache cache = Redis.use();// default

    public static void shortlinkBrowser2Solr() {
	_log.info("启动 shortlinkBrowser solr:" + new Date());
	try {
	    connectCloudSolrServer();
	    addShortlinkBrowseRecordIndex(cloudSolrServer);
	} catch (Exception e) {
	    _log.error("增量数据入solr异常:" + e);
	}
    }

    /**
     * 获取CloudSolrServer
     * 
     * @param zkHost
     * @return
     */
    private static synchronized CloudSolrServer getCloudSolrServer(
	    final String zkHost) {
	if (cloudSolrServer == null) {
	    try {
		_log.info("创建cloudSolrServer");
		cloudSolrServer = new CloudSolrServer(zkHost);
	    } catch (Exception e) {
		_log.info("cloudSolrServer创建异常:" + e);
	    }
	}
	return cloudSolrServer;
    }

    /**
     * 连接CloudSolrServer
     */
    private static void connectCloudSolrServer() {
	CloudSolrServer cloudSolrServer = getCloudSolrServer(PropertieUtils
		.getProperty("zkHost"));
	_log.info("The Cloud SolrServer Instance has benn created!");
	cloudSolrServer.setDefaultCollection(PropertieUtils
		.getProperty("collectionDLNew"));
	cloudSolrServer.setZkClientTimeout(Integer.valueOf(PropertieUtils
		.getProperty("zkClientTimeout")));
	cloudSolrServer.setZkConnectTimeout(Integer.valueOf(PropertieUtils
		.getProperty("zkConnectTimeout")));
	cloudSolrServer.connect();
	_log.info("The cloud Server has been connected !!!!");
    }

    /**
     * 添加索引
     * 
     * @param solrServer
     */
    private static void addShortlinkBrowseRecordIndex(SolrServer solrServer) {
	int page = 1;
	while (true) {
	    // Page<BstShortlinkRequest> shortlinkList = BstShortlinkRequest.dao
	    // .getNotSyncData(page);

	    Page<Record> shortlinkList = BstShortlinkRequest.dao
		    .getNotSyncWideData(page);
	    if (shortlinkList == null || shortlinkList.getList().size() == 0)
		break;
	    Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
	    if (shortlinkList.getList().size() > 0) {
		for (Record detail : shortlinkList.getList()) {
		    try {
			SolrInputDocument doc1 = new SolrInputDocument();
			doc1.addField("cust_id", detail.get("cust_id"));// 唯一ID
			doc1.addField("client_browser",
				detail.getStr("client_browser"));// 用户浏览器
			doc1.addField("client_ip", detail.getStr("client_ip"));// 用户IP
			doc1.addField("client_browse_time", detail
				.getTimestamp("client_browse_time").toString());// 用户浏览时间
			doc1.addField("client_phone",
				detail.getStr("client_phone"));// 用户号码
			doc1.addField("short_code", detail.getStr("short_code"));// 客户短链接
			doc1.addField("request_source",
				detail.get("request_source"));
			doc1.addField("shortlink_flag",
				detail.get("shortlink_flag"));
			doc1.addField("shortlink_once",
				detail.get("shortlink_once"));
			doc1.addField("shortlink_longurl",
				detail.get("shortlink_longurl"));
			doc1.addField("shortlink_cookie",
				detail.get("shortlink_cookie"));
			doc1.addField("cust_code", detail.get("cust_code"));
			doc1.addField("business_flag",
				detail.get("business_flag"));
			doc1.addField("template_code",
				detail.get("template_code"));
			doc1.addField("business_phone",
				detail.get("business_phone"));
			_log.info("doc的field:" + doc1);
			docs.add(doc1);
			// detail.set("is_sync", StaticConstantType.IS_SYNC)
			// .update();
			BstShortlinkRequest.dao.use("bstDB")
				.findById(detail.get("cust_id"))
				.set("is_sync", StaticConstantType.IS_SYNC)
				.update();
		    } catch (Exception e) {
			_log.info("创建索引异常：" + e);
		    }
		}
		try {
		    solrServer.add(docs);
		    solrServer.commit();
		} catch (SolrServerException e) {
		    e.printStackTrace();
		} catch (IOException e) {
		    e.printStackTrace();
		} catch (Exception e) {
		    _log.error("提交索引异常:" + e);
		}
	    }
	    page++;
	}
    }

    /**
     * 查询索引
     * 
     * @param querySql
     * @param currentPage
     * @param perPageSize
     * @return
     */
    public static SolrDocumentList search(String querySql, Integer currentPage,
	    Integer perPageSize) {
	SolrQuery query = new SolrQuery();
	query.setQuery(querySql);
	query.setStart((currentPage - 1) * perPageSize);
	query.setRows(perPageSize);
	query.setFields("client_browser,client_ip,client_browse_time,short_code,cust_phone,"
		+ "request_source, shortlink_flag, shortlink_once,"
		+ "shortlink_longurl, shortlink_cookie, cust_code, business_flag,"
		+ "template_code, business_phone");// 查询字段
	query.setSort("client_browse_time", ORDER.desc);
	try {
	    connectCloudSolrServer();
	    cloudSolrServer.setDefaultCollection("collectionDLNew");
	    QueryResponse response = cloudSolrServer.query(query);
	    SolrDocumentList docs = response.getResults();
	    _log.info("文档个数：" + docs.getNumFound());
	    _log.info("查询时间：" + response.getQTime());
	    return docs;
	} catch (SolrServerException e) {
	    _log.info("SolrServer异常：" + e);
	} catch (Exception e) {
	    _log.info("Solr查询异常：" + e);
	}
	// cloudSolrServer.shutdown();
	return null;
    }
}
